#include "head.hpp"
static const uint16_t port = 8080;
int pipe_fd[2];
void func(int num)
{
    write(pipe_fd[1], "2", 1);
}
int main(int argc, char *argv[])
{
    pipe(pipe_fd);
    signal(2, func);
    son_t list[4];
    memset(list, 0, sizeof(list));
    init_pool(list, 4);
    int socket_fd;
    init_socket(&socket_fd, port);
    int epoll_fd = epoll_create(1);
    add_epoll(epoll_fd, socket_fd);
    for (int i = 0; i < 4; i++)
    {
        add_epoll(epoll_fd, list[i].local_socket);
    }
    add_epoll(epoll_fd, pipe_fd[0]);
    while (true)
    {
        struct epoll_event events[4];
        memset(events, 0, sizeof(events));
        int epoll_num = epoll_wait(epoll_fd, events, 4, -1);
        for (int i = 0; i < epoll_num; i++)
        {
            int fd = events[i].data.fd;
            if (fd == socket_fd)
            {
                int net_fd = accept(socket_fd, nullptr, nullptr);
                to_son(list, 4, net_fd);
                close(net_fd);
            }
            else if (fd == pipe_fd[0])
            {
                char buffer[10] = {0};
                read(pipe_fd[0], buffer, sizeof(buffer));
                printf("2号信号过来了\n");
                for (int k = 0; k < 4; k++)
                {
                    local_send(list[k].local_socket, 0, -1);
                }
                for (int k = 0; k < 4; k++)
                {
                    wait(nullptr);
                }
                exit(0);
            }
            else
            {
                char buf[1024] = {0};
                recv(fd, buf, sizeof(buf), 0);
                for (int k = 0; k < 4; k++)
                {
                    if (fd == list[k].local_socket)
                    {
                        list[k].status = FREE;
                        break;
                    }
                }
            }
        }
    }
    return 0;
}